// ReactorEx3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "SOCK_WrapperFacade.h"
#include "AlarmEvent.h"
#include "LogEvent.h"
#include "PatientEvent.h"
#include "LogAcceptor.h"
#include "Reactor.h"
#include "Acceptor.h"

#define DEFAULT_PORT_LOG		27015
#define DEFAULT_PORT_PATIENT	27016
#define DEFAULT_PORT_ALARM		27017

int _tmain(int argc, _TCHAR* argv[])
{

	unsigned long address = 0x7F000001;

	// Convert server address to hexadecimal base.
	if (argc > 1) {
		printf("Server set as %s\n", argv[1]);
		address = ntohl(inet_addr((const char*)argv[1]));
	} else
		printf("Server set as localhost\n");

	// On windows start socket 2.2 system
	WSADATA wsa_data;
	WORD version_requested = MAKEWORD(2, 2);
	int error = WSAStartup(version_requested, &wsa_data);
	if (error != 0) return -1;

	INET_Addr logAddr(DEFAULT_PORT_LOG, address);
	SOCK_Acceptor *logServer = new SOCK_Acceptor(logAddr); 

	INET_Addr patientAddr(DEFAULT_PORT_PATIENT, address);
	SOCK_Acceptor *patientServer = new SOCK_Acceptor(patientAddr); 
	
	INET_Addr alarmAddr(DEFAULT_PORT_ALARM, address);
	SOCK_Acceptor *alarmServer = new SOCK_Acceptor(alarmAddr); 

#if 1
	// Test with all event services (Log, Patient and Alarm)
	Acceptor<LogEvent> logAcceptor(Reactor::instance(), logServer);
	Acceptor<PatientEvent> patientAcceptor(Reactor::instance(), patientServer);
	Acceptor<AlarmEvent> alarmAcceptor(Reactor::instance(), alarmServer);
#else
	// Test with one log event service
	LogAcceptor logAcceptor(Reactor::instance(), logServer);
#endif
	
	// Simulate generating events (Alarm, Log and Patient)
	while (1)
		Reactor::instance()->handleEvents();

/* TESTING first version
	// Creates reactor 
	Reactor *itsReactor = Reactor::instance();

	// Register event handlers
	itsReactor->registerHandler(*(new AlarmEvent(itsReactor, (HANDLE)1)), READ_EVENT);
	itsReactor->registerHandler(*(new LogEvent(itsReactor, (HANDLE)2)), READ_EVENT);
	itsReactor->registerHandler(*(new PatientEvent(itsReactor, (HANDLE)3)), READ_EVENT);
	itsReactor->registerHandler(*(new LogAcceptor(itsReactor, (HANDLE)4)), ACCEPT_EVENT);

	itsReactor->handleEvents();

	Sleep(2000);
*/

	return 0;
}

